/**
 * 主题管理模块
 * @module $ui/utils/skin
 * @author chenhuachun
 */
import {get as getCache, save, LOCAL} from './storage'

const setTheme = require('../import/theme/' + process.env.NODE_ENV)
let cacheValue = null
const LOCAL_CACHE_KEY = '__MY_SKIN__'

function createCacheKey(app) {
  return app ? `__MY_SKIN_${app}__` : LOCAL_CACHE_KEY
}

/**
 * 更换主题
 * @param {string} theme 主题名
 * @param {string} app 子应用名称
 */
export function change(theme, app) {
  cacheValue = theme
  save(createCacheKey(app), cacheValue, LOCAL)
  setTheme(theme, app)
}

/**
 * 获取当前主题名
 * @return {string}
 */
export function get(app) {
  return cacheValue || getCache(createCacheKey(app), LOCAL) || null
}

/**
 * 载入主题，页面初始化时使用
 */
export function load(app) {
  const theme = get(app) || 'default'
  change(theme, app)
}

/**
 * Skin Mixin
 */
export default function (app) {
  return {
    methods: {
      changeTheme(name) {
        change(name, app)
      },
      storageChangeHandler(evt) {
        
        if (!evt.key.startsWith(LOCAL_CACHE_KEY)) return
        this.changeTheme(evt.newValue)
      }
    },
    created() {
      window.addEventListener('storage', this.storageChangeHandler)
      load(app)
    },
    beforeDestroy() {
      window.removeEventListener('storage', this.storageChangeHandler)
    }
  }
}
